package org.eclipse.football;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DefPlayerServlet extends HttpServlet implements Servlet {
	// Override doPost function
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Read in information submitted by form
		String button = request.getParameter("Def Player Button");
		String name = request.getParameter("name");
		
		// Obtain existing team
		Team team = (Team) request.getSession(true).getAttribute("team");
		
		// Obtain existing league
		League league = (League) request.getSession(true).getAttribute("league");
		
		// Declare a defensive player variable
		DefPlayer player;
		
		if(button.equals("Add Defensive Player")){
			// Make sure that new players name is not null or blank and team is not null
			if(name != null && !name.equalsIgnoreCase("") && team != null){
				// If not then create a player with the given name and team
				player = new DefPlayer(name, "");
		
				// Add the new player to this team
				team.addDefPlayer(player);
			}
		
		}
		else if (button.equals("Fire!")){
			
			if(name != null && !name.equalsIgnoreCase("") && team != null){
				player = new DefPlayer(name, "");
				team.removeDefPlayer(player);
			}
		}
		
		// Write the current state of the league out to a file
		league.writeState("league.txt");
		
		// Set league in the session
		request.getSession().setAttribute("league", league);
		
		// Set team in the session
		request.getSession().setAttribute("team", team);
		
		// Set all 3 player types to null in the session
		request.getSession().setAttribute("off", null);
		request.getSession().setAttribute("def", null);
		request.getSession().setAttribute("kicker", null);
		
		// Forward control back to stats.jsp
		getServletContext().getRequestDispatcher("/TeamPage.jsp").forward(request, response);
		
		// TODO Auto-generated method stub
		//super.doPost(request, response);
	}

}

